{% extends "base.html" %}

{% block title %}专业K线图 - 量化股票数据分析系统{% endblock %}

{% block extra_css %}
<style>
    /* 深色主题样式 */
    body {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
    }
    
    .chart-container {
        background: #1e222d;
        border-radius: 12px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.4);
        padding: 0;
        overflow: hidden;
    }
    
    .chart-header {
        background: #2a2e39;
        padding: 15px 20px;
        border-bottom: 1px solid #363c4e;
    }
    
    .symbol-info {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    
    .symbol-name {
        font-size: 24px;
        font-weight: 600;
        color: #fff;
    }
    
    .price-info {
        display: flex;
        align-items: baseline;
        gap: 15px;
    }
    
    .current-price {
        font-size: 28px;
        font-weight: 700;
        color: #fff;
    }
    
    .price-change {
        font-size: 18px;
        font-weight: 500;
    }
    
    .price-up { color: #26a69a; }
    .price-down { color: #ef5350; }
    
    .toolbar {
        background: #2a2e39;
        padding: 10px 20px;
        border-bottom: 1px solid #363c4e;
        display: flex;
        gap: 10px;
        align-items: center;
        flex-wrap: wrap;
    }
    
    .btn-group {
        display: flex;
        background: #1e222d;
        border-radius: 6px;
        overflow: hidden;
    }
    
    .btn-group button {
        background: transparent;
        border: none;
        color: #9ca3af;
        padding: 8px 16px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s;
    }
    
    .btn-group button:hover {
        background: #363c4e;
        color: #fff;
    }
    
    .btn-group button.active {
        background: #5367ff;
        color: #fff;
    }
    
    #chart {
        height: 500px;
        background: #1e222d;
    }
    
    .indicator-list {
        background: #2a2e39;
        padding: 15px 20px;
        border-top: 1px solid #363c4e;
        display: flex;
        gap: 15px;
        flex-wrap: wrap;
    }
    
    .indicator-toggle {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #9ca3af;
        cursor: pointer;
        transition: color 0.3s;
    }
    
    .indicator-toggle:hover {
        color: #fff;
    }
    
    .indicator-toggle input[type="checkbox"] {
        width: 18px;
        height: 18px;
        cursor: pointer;
    }
    
    .indicator-toggle.active {
        color: #5367ff;
    }
    
    .loading-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(30, 34, 45, 0.9);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1000;
    }
    
    .spinner {
        width: 50px;
        height: 50px;
        border: 3px solid #363c4e;
        border-top-color: #5367ff;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        to { transform: rotate(360deg); }
    }
    
    .stock-selector {
        background: #1e222d;
        border: 1px solid #363c4e;
        color: #fff;
        padding: 8px 12px;
        border-radius: 6px;
        min-width: 200px;
        font-size: 14px;
    }
    
    .stock-selector option {
        background: #1e222d;
        color: #fff;
    }
    
    .refresh-btn {
        background: #5367ff;
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 6px;
        cursor: pointer;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 5px;
        transition: background 0.3s;
    }
    
    .refresh-btn:hover {
        background: #4256e8;
    }
    
    .stats-container {
        background: #2a2e39;
        padding: 15px 20px;
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 20px;
        border-top: 1px solid #363c4e;
    }
    
    .stat-item {
        text-align: center;
    }
    
    .stat-label {
        color: #9ca3af;
        font-size: 12px;
        margin-bottom: 5px;
    }
    
    .stat-value {
        color: #fff;
        font-size: 18px;
        font-weight: 600;
    }
</style>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="chart-container">
        <!-- 图表头部 -->
        <div class="chart-header">
            <div class="symbol-info">
                <div>
                    <h1 class="symbol-name" id="symbolName">
                        <span id="symbolCode">000001</span> - <span id="stockName">平安银行</span>
                    </h1>
                </div>
                <div class="price-info">
                    <span class="current-price" id="currentPrice">--</span>
                    <span class="price-change price-up" id="priceChange">--</span>
                    <span class="price-change price-up" id="priceChangePercent">--</span>
                </div>
            </div>
        </div>
        
        <!-- 工具栏 -->
        <div class="toolbar">
            <!-- 股票选择器 -->
            <select id="stockSelector" class="stock-selector">
                <option value="">加载中...</option>
            </select>
            
            <!-- 时间周期 -->
            <div class="btn-group" id="intervalButtons">
                <button data-interval="1m">1分钟</button>
                <button data-interval="5m">5分钟</button>
                <button data-interval="15m">15分钟</button>
                <button data-interval="30m">30分钟</button>
                <button data-interval="1h">1小时</button>
                <button data-interval="1d" class="active">日线</button>
                <button data-interval="1w">周线</button>
                <button data-interval="1M">月线</button>
            </div>
            
            <!-- 图表类型 -->
            <div class="btn-group" id="chartTypeButtons">
                <button data-type="candlestick" class="active">K线</button>
                <button data-type="line">折线</button>
                <button data-type="area">面积</button>
                <button data-type="bar">柱状图</button>
            </div>
            
            <!-- 刷新按钮 -->
            <button class="refresh-btn" onclick="refreshChart()">
                <svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
                    <path d="M11.534 7h3.932a.25.25 0 0 1 .192.41l-1.966 2.36a.25.25 0 0 1-.384 0l-1.966-2.36a.25.25 0 0 1 .192-.41zm-11 2h3.932a.25.25 0 0 0 .192-.41L2.692 6.23a.25.25 0 0 0-.384 0L.342 8.59A.25.25 0 0 0 .534 9z"/>
                    <path fill-rule="evenodd" d="M8 3c-1.552 0-2.94.707-3.857 1.818a.5.5 0 1 1-.771-.636A6.002 6.002 0 0 1 13.917 7H12.9A5.002 5.002 0 0 0 8 3zM3.1 9a5.002 5.002 0 0 0 8.757 2.182.5.5 0 1 1 .771.636A6.002 6.002 0 0 1 2.083 9H3.1z"/>
                </svg>
                刷新
            </button>
        </div>
        
        <!-- 主图表 -->
        <div id="chart" class="relative">
            <div class="loading-overlay" id="loadingOverlay">
                <div class="spinner"></div>
            </div>
        </div>
        
        <!-- 技术指标 -->
        <div class="indicator-list">
            <label class="indicator-toggle">
                <input type="checkbox" id="ma" checked>
                <span>移动平均线 (MA)</span>
            </label>
            <label class="indicator-toggle">
                <input type="checkbox" id="ema">
                <span>指数移动平均 (EMA)</span>
            </label>
            <label class="indicator-toggle">
                <input type="checkbox" id="volume" checked>
                <span>成交量</span>
            </label>
            <label class="indicator-toggle">
                <input type="checkbox" id="macd">
                <span>MACD</span>
            </label>
            <label class="indicator-toggle">
                <input type="checkbox" id="rsi">
                <span>RSI</span>
            </label>
            <label class="indicator-toggle">
                <input type="checkbox" id="bollinger">
                <span>布林带</span>
            </label>
        </div>
        
        <!-- 统计信息 -->
        <div class="stats-container">
            <div class="stat-item">
                <div class="stat-label">开盘价</div>
                <div class="stat-value" id="openPrice">--</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">最高价</div>
                <div class="stat-value" id="highPrice">--</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">最低价</div>
                <div class="stat-value" id="lowPrice">--</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">成交量</div>
                <div class="stat-value" id="volumeValue">--</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">换手率</div>
                <div class="stat-value" id="turnover">--</div>
            </div>
            <div class="stat-item">
                <div class="stat-label">市盈率</div>
                <div class="stat-value" id="pe">--</div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
    <!-- TradingView Lightweight Charts (本地) -->
    <script src="{{ url_for('static', filename='js/lightweight-charts.min.js') }}"></script>
<script>
let chart = null;
let candlestickSeries = null;
let volumeSeries = null;
let maSeries = {};
let currentSymbol = '000001';
let currentInterval = '1d';
let chartType = 'candlestick';

// 初始化图表
function initChart() {
    const chartContainer = document.getElementById('chart');
    
    chart = LightweightCharts.createChart(chartContainer, {
        width: chartContainer.clientWidth,
        height: 500,
        layout: {
            background: { color: '#1e222d' },
            textColor: '#9ca3af',
        },
        grid: {
            vertLines: { color: '#363c4e' },
            horzLines: { color: '#363c4e' },
        },
        crosshair: {
            mode: LightweightCharts.CrosshairMode.Normal,
        },
        priceScale: {
            borderColor: '#363c4e',
        },
        timeScale: {
            borderColor: '#363c4e',
            timeVisible: true,
            secondsVisible: false,
        },
    });
    
    // 检查LightweightCharts是否正确加载
    if (typeof LightweightCharts === 'undefined') {
        console.error('TradingView Lightweight Charts library not loaded');
        alert('图表库加载失败，请刷新页面重试');
        return;
    }
    
    // 创建K线系列
    if (chartType === 'candlestick') {
        candlestickSeries = chart.addCandlestickSeries({
            upColor: '#26a69a',
            downColor: '#ef5350',
            borderUpColor: '#26a69a',
            borderDownColor: '#ef5350',
            wickUpColor: '#26a69a',
            wickDownColor: '#ef5350',
        });
    } else if (chartType === 'line') {
        candlestickSeries = chart.addLineSeries({
            color: '#5367ff',
            lineWidth: 2,
        });
    } else if (chartType === 'area') {
        candlestickSeries = chart.addAreaSeries({
            lineColor: '#5367ff',
            topColor: 'rgba(83, 103, 255, 0.5)',
            bottomColor: 'rgba(83, 103, 255, 0.1)',
        });
    }
    
    // 响应式调整
    window.addEventListener('resize', () => {
        chart.applyOptions({
            width: chartContainer.clientWidth,
        });
    });
}

// 加载股票列表
async function loadStocks() {
    try {
        const response = await fetch('/api/stocks');
        const stocks = await response.json();
        
        const selector = document.getElementById('stockSelector');
        selector.innerHTML = '';
        
        // 如果没有股票数据，显示提示
        if (stocks.length === 0) {
            const option = document.createElement('option');
            option.value = '';
            option.textContent = '暂无股票数据';
            selector.appendChild(option);
            return;
        }
        
        stocks.forEach(stock => {
            const option = document.createElement('option');
            option.value = stock.symbol;
            option.textContent = `${stock.symbol} - ${stock.name}`;
            selector.appendChild(option);
        });
        
        // 设置默认选中
        if (stocks.length > 0 && !stocks.find(s => s.symbol === currentSymbol)) {
            currentSymbol = stocks[0].symbol;
        }
        selector.value = currentSymbol;
    } catch (error) {
        console.error('Failed to load stocks:', error);
        const selector = document.getElementById('stockSelector');
        selector.innerHTML = '<option value="">加载失败</option>';
    }
}

// 加载K线数据
async function loadChartData(symbol, interval) {
    if (!symbol) {
        console.log('No symbol provided');
        showLoading(false);
        return;
    }
    
    console.log(`Loading data for ${symbol} with interval ${interval}`);
    showLoading(true);
    
    try {
        // 直接获取股票数据，不使用K线API
        const response = await fetch(`/api/test_stock/${symbol}?period=${interval}&days=120`);
        const result = await response.json();
        
        if (result.error) {
            throw new Error(result.error);
        }
        
        console.log(`Received ${result.data.length} data points`);
        
        // 更新股票信息
        updateStockInfo(result);
        
        // 转换数据格式为TradingView格式
        const klineData = [];
        const volumeData = [];
        
        if (result.data && result.data.length > 0) {
            // 按日期排序
            result.data.sort((a, b) => {
                const dateA = new Date(a.date || a.Date);
                const dateB = new Date(b.date || b.Date);
                return dateA - dateB;
            });
            
            for (let i = 0; i < result.data.length; i++) {
                const item = result.data[i];
                const dateStr = item.date || item.Date;
                console.log('Processing date:', dateStr);
                
                // Convert date string to YYYY-MM-DD format for LightweightCharts
                let timeValue;
                if (dateStr.includes('T')) {
                    // ISO format
                    timeValue = dateStr.split('T')[0];
                } else {
                    // Simple date format
                    timeValue = dateStr;
                }
                
                const open = parseFloat(item.open);
                const high = parseFloat(item.high);
                const low = parseFloat(item.low);
                const close = parseFloat(item.close);
                
                // Validate OHLC data
                if (isNaN(open) || isNaN(high) || isNaN(low) || isNaN(close)) {
                    console.warn('Invalid OHLC data at', dateStr, item);
                    continue;
                }
                
                if (chartType === 'candlestick') {
                    klineData.push({
                        time: timeValue,
                        open: open,
                        high: high,
                        low: low,
                        close: close,
                    });
                } else {
                    klineData.push({
                        time: timeValue,
                        value: close,
                    });
                }
                
                // 成交量数据
                if (item.volume) {
                    volumeData.push({
                        time: timeValue,
                        value: parseFloat(item.volume),
                        color: close >= open ? '#26a69a' : '#ef5350',
                    });
                }
            }
        }
        
        console.log(`Setting ${klineData.length} data points to chart`);
        console.log('First few data points:', klineData.slice(0, 3));
        console.log('Chart type:', chartType);
        console.log('Candlestick series:', candlestickSeries);
        
        // 设置数据
        if (klineData.length > 0) {
            candlestickSeries.setData(klineData);
            console.log('Data set to candlestick series successfully');
            
            // 添加成交量到独立的价格刻度
            if (document.getElementById('volume').checked && volumeData.length > 0) {
                // 只有当volumeSeries已经存在且不为undefined时才移除
                if (volumeSeries && chart) {
                    try {
                        chart.removeSeries(volumeSeries);
                    } catch (e) {
                        console.warn('Could not remove volume series:', e);
                    }
                    volumeSeries = null;
                }
                
                volumeSeries = chart.addHistogramSeries({
                    color: '#26a69a',
                    priceFormat: {
                        type: 'volume',
                    },
                    priceScaleId: 'volume', // 使用独立的价格刻度
                    scaleMargins: {
                        top: 0.7, // 成交量占用底部30%的空间
                        bottom: 0,
                    },
                });
                
                volumeSeries.setData(volumeData);
            }
        } else {
            console.error('No data to display');
            alert('暂无数据可显示');
        }
        
        // 添加MA线
        if (document.getElementById('ma').checked) {
            addMovingAverage(klineData, [5, 10, 20]);
        }
        
        // 适应内容
        chart.timeScale().fitContent();
        
        // 更新统计信息
        if (klineData.length > 0) {
            updateStats(klineData[klineData.length - 1], volumeData.length > 0 ? volumeData[volumeData.length - 1] : null);
        }
        
    } catch (error) {
        console.error('Failed to load chart data:', error);
        alert('加载数据失败: ' + error.message);
    } finally {
        showLoading(false);
    }
}

// 添加移动平均线
function addMovingAverage(data, periods) {
    periods.forEach(period => {
        const maData = [];
        
        for (let i = period - 1; i < data.length; i++) {
            let sum = 0;
            for (let j = 0; j < period; j++) {
                const price = data[i - j].close || data[i - j].value;
                if (isNaN(price)) {
                    console.warn('Invalid price data for MA calculation:', data[i - j]);
                    continue;
                }
                sum += price;
            }
            if (sum > 0) {
                maData.push({
                    time: data[i].time,
                    value: sum / period,
                });
            }
        }
        
        // 移除旧的MA线
        if (maSeries[`ma${period}`] && chart) {
            try {
                chart.removeSeries(maSeries[`ma${period}`]);
            } catch (e) {
                console.warn(`Could not remove MA${period} series:`, e);
            }
            maSeries[`ma${period}`] = null;
        }
        
        // 添加新的MA线
        const colors = {
            5: '#3b82f6',
            10: '#8b5cf6',
            20: '#f59e0b',
        };
        
        maSeries[`ma${period}`] = chart.addLineSeries({
            color: colors[period] || '#666',
            lineWidth: 2,
            title: `MA${period}`,
        });
        
        maSeries[`ma${period}`].setData(maData);
    });
}

// 更新股票信息
function updateStockInfo(data) {
    const symbolElement = document.getElementById('symbolCode');
    const nameElement = document.getElementById('stockName');
    if (symbolElement) symbolElement.textContent = data.symbol;
    if (nameElement) nameElement.textContent = data.name;
}

// 更新统计信息
function updateStats(latestBar, volumeBar) {
    if (latestBar) {
        document.getElementById('currentPrice').textContent = latestBar.close ? latestBar.close.toFixed(2) : '--';
        document.getElementById('openPrice').textContent = latestBar.open ? latestBar.open.toFixed(2) : '--';
        document.getElementById('highPrice').textContent = latestBar.high ? latestBar.high.toFixed(2) : '--';
        document.getElementById('lowPrice').textContent = latestBar.low ? latestBar.low.toFixed(2) : '--';
        
        // 计算涨跌
        if (latestBar.open && latestBar.close) {
            const change = latestBar.close - latestBar.open;
            const changePercent = (change / latestBar.open) * 100;
            
            document.getElementById('priceChange').textContent = change >= 0 ? `+${change.toFixed(2)}` : change.toFixed(2);
            document.getElementById('priceChangePercent').textContent = `${changePercent >= 0 ? '+' : ''}${changePercent.toFixed(2)}%`;
            
            const changeElements = document.querySelectorAll('#priceChange, #priceChangePercent');
            changeElements.forEach(el => {
                el.classList.remove('price-up', 'price-down');
                el.classList.add(change >= 0 ? 'price-up' : 'price-down');
            });
        }
    }
    
    if (volumeBar && volumeBar.value) {
        const volumeElement = document.getElementById('volumeValue');
        if (volumeElement) volumeElement.textContent = formatVolume(volumeBar.value);
    } else {
        const volumeElement = document.getElementById('volumeValue');
        if (volumeElement) volumeElement.textContent = '--';
    }
}

// 格式化成交量
function formatVolume(volume) {
    // 检查volume是否有效
    if (!volume || isNaN(volume)) {
        return '--';
    }
    
    volume = Number(volume);
    
    if (volume >= 100000000) {
        return (volume / 100000000).toFixed(2) + '亿';
    } else if (volume >= 10000) {
        return (volume / 10000).toFixed(2) + '万';
    }
    return volume.toFixed(0);
}

// 显示/隐藏加载动画
function showLoading(show) {
    document.getElementById('loadingOverlay').style.display = show ? 'flex' : 'none';
}

// 刷新图表
function refreshChart() {
    loadChartData(currentSymbol, currentInterval);
}

// 事件监听
document.addEventListener('DOMContentLoaded', function() {
    console.log('Page loaded, initializing chart...');
    // 立即显示加载动画
    showLoading(true);
    
    // 检查库是否已加载
    function checkAndInit() {
        if (typeof LightweightCharts !== 'undefined') {
            console.log('LightweightCharts library loaded');
            // 库已加载，立即初始化
            initChart();
            
            // 异步加载数据
            loadStocks().then(() => {
                console.log('Stocks loaded, now loading chart data...');
                return loadChartData(currentSymbol, currentInterval);
            }).then(() => {
                console.log('Chart initialized successfully');
            }).catch(error => {
                console.error('Initialization error:', error);
                showLoading(false);
            });
        } else {
            console.log('Waiting for LightweightCharts library...');
            // 库未加载，等待100ms后重试
            setTimeout(checkAndInit, 100);
        }
    }
    
    // 立即开始检查
    checkAndInit();
    
    // 股票选择
    document.getElementById('stockSelector').addEventListener('change', function(e) {
        currentSymbol = e.target.value;
        if (currentSymbol) {
            loadChartData(currentSymbol, currentInterval);
        }
    });
    
    // 时间周期切换
    document.querySelectorAll('#intervalButtons button').forEach(button => {
        button.addEventListener('click', function() {
            document.querySelectorAll('#intervalButtons button').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            currentInterval = this.dataset.interval;
            loadChartData(currentSymbol, currentInterval);
        });
    });
    
    // 图表类型切换
    document.querySelectorAll('#chartTypeButtons button').forEach(button => {
        button.addEventListener('click', function() {
            document.querySelectorAll('#chartTypeButtons button').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            chartType = this.dataset.type;
            
            // 重新初始化图表
            chart.remove();
            initChart();
            loadChartData(currentSymbol, currentInterval);
        });
    });
    
    // 技术指标切换
    document.querySelectorAll('.indicator-toggle input').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            loadChartData(currentSymbol, currentInterval);
        });
    });
});
</script>
{% endblock %}